<script setup lang="ts">
import type {
  OauthLoginState,
} from '#/auth/Login'
import type { OauthLoginInfo } from '@/utils/oauth'
import { getOauthLoginInfo } from '@/utils/oauth'

const router = useRouter()
const userStore = useUserStoreHook()
let oauthLoginInfo = $ref<OauthLoginInfo>({
  loginType: '',
  type: '',
  redirectUrl: '',
})

/**
 * 获取地址栏参数
 * @param name 地址栏参数的key
 */
function getQueryString(name: string) {
  const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i')
  const r = window.location.search.slice(1).match(reg)
  if (r != null) {
    return decodeURIComponent(r[2])
  }
  return null
}

// 跳转
function redirectUrl() {
  router.replace({ path: oauthLoginInfo.redirectUrl })
}

function login(code: string, state?: string) {
  userStore.login({
    code,
    state,
    loginType: oauthLoginInfo.loginType,
    type: oauthLoginInfo.type,
    grant_type: 'oauth:grant-type:third',
  } as OauthLoginState).then(() => {
    Message({
      message: '登录成功',
      type: 'success',
    })
    // 移除code和state参数
    removeQueryParam('code')
    removeQueryParam('state')
    redirectUrl()
  }).catch(() => {
    router.replace('/')
  })
}

function removeQueryParam(param) {
  const url = new URL(window.location.href)
  url.searchParams.delete(param) // 删除指定的查询参数

  // 构建新的URL，不包含被删除的查询参数
  const newUrl = url.origin + url.pathname + url.hash

  // 使用浏览器的历史API更新URL，不会导致页面刷新
  window.history.replaceState({}, '', newUrl)
}

onMounted(() => {
  oauthLoginInfo = getOauthLoginInfo()
  const code = getQueryString('code')
  const state = getQueryString('state') || undefined
  if (code == null || code === undefined || code === '') {
    router.replace('/')
    return
  }
  login(code, state)
})
</script>

<template>
  <div v-loading="true" element-loading-text="Login..." class="loading" />
</template>

<style scoped>
.loading {
  width: 100vw;
  height: 100vh;
}
</style>
